#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json
from datetime import datetime, date

from excel.PruTuutDb import PruTuutDb


class MemberWieghtObj:
    id: float(0)
    MEMBER_ID: ""
    weight_json: ""

    pruTuut_conn = PruTuutDb.get_pool()

    def __init__(self):
        return

    @staticmethod
    def split_params(params):
        g_param = []
        if params['member_id'] is not None and len(params['member_id']) > 0:
            g_param.append('`member_id`=' + "\'" + params['member_id'] + "\'")
        if params['weight_json'] is not None and len(params['weight_json']) > 0:
            g_param.append('`weight_json`=' + "\'" + params['weight_json'] + "\'")
        return ', '.join(str(i) for i in g_param)

    @staticmethod
    def concat_datas(g_param):
        # 获取当前时间
        arry = []
        # 注册用户需要计算下标准热量缺口值
        weight_json = {"height": float(g_param["height"]),
                       "weight": float(g_param["weight"]),
                       "age": int(g_param["age"]),
                       "bmi": float(g_param["bmi"]),
                       "bodyFatRat": float(g_param["bodyFatRat"]),
                       "heatgap": int(g_param["heatgap"])}
        arry.append(g_param['member_id'])
        arry.append(json.dumps(weight_json, ensure_ascii=False))
        _res = []
        for _val in arry:
            if isinstance(_val, str):
                _res.append(f"\'{_val}\'")
            else:
                if _val is None:
                    _res.append("null")
                else:
                    _res.append(_val)
        return ', '.join(str(i) for i in _res)

    @staticmethod
    def load_db_2_dict(data):
        # `id`,`member_id`,`member_code`,`weight_json`,`name`,`uname`,`sex`,`STATUS`
        g_param = {}
        g_param["id"] = data[0]
        g_param["member_id"] = data[1]
        g_param["member_sno"] = data[2]
        json_obj = json.loads(str(data[3]))
        g_param["height"] = json_obj['height']
        g_param["weight"] = json_obj['weight']
        g_param["age"] = json_obj['age']
        try:
            g_param["heatgap"] = json_obj['heatgap']
        except Exception as e:
            g_param["heatgap"] = 0
        g_param["name"] = data[4]
        g_param["sex"] = data[6]
        g_param["status"] = data[7]
        return g_param

    # 标记为true时候，从DBA中读取数据，附带ID主键，标记为false时候忽略自增型字段ID
    @staticmethod
    def to_string(with_flg):
        g_param = []
        if with_flg:
            g_param.append("`mem_member_weight`.`id`")
            g_param.append("`mem_member_weight`.`member_id`")
            g_param.append("`mem_member_weight`.`weight_json`")
        else:
            g_param.append("`member_id`")
            g_param.append("`weight_json`")
        return ', '.join(str(i) for i in g_param)

    @staticmethod
    def str_2_date(input_str) -> object:
        try:
            # 定义日期时间格式化字符串
            format_str = '%Y-%m-%dT%H:%M:%S.%fZ'
            # 将字符串按指定格式转换为datetime对象
            dt_obj = datetime.strptime(input_str, format_str)
            # 提取年、月、日信息并构建Date对象
            year = dt_obj.year
            month = dt_obj.month
            day = dt_obj.day
            date_obj = date(year=year, month=month, day=day)
            return date_obj
        except Exception as e:
            return input_str

    # 根据会员基础参数，返回对应的热量缺口
    # TODO 2024-03-16 1-1 会员注册时候加入体质计算数据
    @staticmethod
    def cal_member_heat_gap(mem: object) -> int:
        _default_calor_gap = int(300)
        # 优先获取会员标记的热量值
        try:
            if mem["heatgap"] is not None and int(mem["heatgap"]) > 0:
                return int(mem["heatgap"])
        except KeyError as e:
            print("新会员注册，设定默认热量缺口")
        dict_keys = ["maleStdWeight", "femaleStdWeight"]
        # 根据会员的基础参数，判断热量匹配表数据，计算标准热量缺口
        fetch_sql = f" SELECT `id`,`key`,`key_eng`,`col`,`val`,`add_time` FROM `sys_dict` WHERE 1=1 AND `col` = '标准体重'"
        dict_items = MemberWieghtObj.pruTuut_conn.sql_execute(fetch_sql)
        if len(dict_items) > 0:
            check_datas = [
                {"id": item[0], "key": item[1], "key_eng": item[2], "col": item[3], "val": item[4], "add_time": item[5]}
                for item in dict_items]
            if mem['sex'] == "1":
                is_even = lambda x: x['key_eng'] == "femaleStdWeight"
                _checks = list(filter(is_even, check_datas))
            else:
                is_even = lambda x: x['key_eng'] == "maleStdWeight"
                _checks = list(filter(is_even, check_datas))
        cal_mem_feature_data(mem, check_std_array=_checks[0]["val"])
        # 根据特征计算对应的热量缺口
        # if calorGapNum > 0:
        #     calorGap = calories - calorGapNum
        # else:
        #     calorGap = calories - 450
        return _default_calor_gap



def test_1():
    import random
    start = 150  # 起始值（包含）
    end = 200  # 结束值（不包含）
    count = 3  # 需要生成的随机整数个数
    random_list = [random.randint(start, end) for _ in range(count)]
    for i in range(len(random_list)):
        w_start = 50  # 起始值（包含）
        w_end = 80  # 结束值（不包含）
        obj = {"height": random_list[i], "weight": random.randint(w_start, w_end)}
        print(json.dumps(obj, sort_keys=True, ensure_ascii=False, indent=4))


def cal_mem_feature_data(mem, check_std_array):
    # 1.1 标准数据
    _verify_std_arry = json.loads(check_std_array)
    _frm_arrays = []
    _feature_arrays = []
    # 1.2 身高， 体重， BMI 进行枚举计算
    int_mem_height = int(float(mem["height"]))
    int_mem_weight = int(float(mem["weight"]))
    mem_BMI = mem["bmi"]
    # 1.3 判断身高所在的标准值
    check_h_flg =0
    filtered_objects_stds = [obj for obj in _verify_std_arry if obj['height'] == int_mem_height]
    if len(filtered_objects_stds) == 0:
        check_h_flg = 0
        check_w_flg = 0
        check_bmi_flg = 0
    else:
        filtered_objects = filtered_objects_stds[0]
        check_w_flg = 1 if int_mem_weight - filtered_objects["weight"] > 0 else -1
        check_bmi_flg = 1 if mem_BMI - filtered_objects["bmi"] > 0 else -1
    _frm_arrays.append({"height":check_h_flg,"weight":check_w_flg,"bmi":check_bmi_flg})
    _feature_arrays.append(str(check_h_flg))
    _feature_arrays.append(str(check_w_flg))
    _feature_arrays.append(str(check_bmi_flg))
    # 1.4 判断体重所在的标准值
    check_w_flg =0
    filtered_objects_max = [obj for obj in _verify_std_arry if obj['weight'] <= int_mem_weight]
    filtered_objects_min = [obj for obj in _verify_std_arry if int_mem_weight <= obj['weight']]
    if len(filtered_objects_max) >0 and len(filtered_objects_min)>0:
        filtered_objects = filtered_objects_min[0]
    else:
        if len(filtered_objects_max) > 0 and len(filtered_objects_min) ==0:
            filtered_objects = filtered_objects_max[-1]
        else:
            filtered_objects = filtered_objects_min[0]
    check_h_flg = 1 if int_mem_height - filtered_objects["height"] > 0 else -1
    check_bmi_flg = 1 if mem_BMI - filtered_objects["bmi"] > 0 else -1
    _frm_arrays.append({"height": check_h_flg, "weight": check_w_flg, "bmi": check_bmi_flg})
    _feature_arrays.append(str(check_h_flg))
    _feature_arrays.append(str(check_w_flg))
    _feature_arrays.append(str(check_bmi_flg))
    # 1.5 判断BMI所在的标准值
    check_bmi_flg = 0
    filtered_objects_max = [obj for obj in _verify_std_arry if obj['bmi'] <= mem_BMI]
    filtered_objects_min = [obj for obj in _verify_std_arry if mem_BMI <= obj['bmi']]
    if len(filtered_objects_max) > 0 and len(filtered_objects_min) > 0:
        filtered_objects = filtered_objects_min[0]
    else:
        if len(filtered_objects_max) > 0 and len(filtered_objects_min) == 0:
            filtered_objects = filtered_objects_max[-1]
        else:
            filtered_objects = filtered_objects_min[0]
    check_h_flg = 1 if int_mem_height - filtered_objects["height"] > 0 else -1
    check_w_flg = 1 if int_mem_weight - filtered_objects["weight"] > 0 else -1
    _frm_arrays.append({"height": check_h_flg, "weight": check_w_flg, "bmi": check_bmi_flg})
    _feature_arrays.append(str(check_h_flg))
    _feature_arrays.append(str(check_w_flg))
    _feature_arrays.append(str(check_bmi_flg))
    # TODO 打印计算数据特征
    # print(json.dumps(_frm_arrays, ensure_ascii=False))
    return ".".join(_feature_arrays).replace(".","")

if __name__ == '__main__':
    # 男性标准数据
    _verify_str = '[{"height":160,"weight":52.5,"BMI":20.5078125},{"height":161,"weight":54,"BMI":20.8325296091972},{"height":162,"weight":55.5,"BMI":21.1476909007773},{"height":163,"weight":57,"BMI":21.4535737137265},{"height":164,"weight":58.5,"BMI":21.7504461629982},{"height":165,"weight":60,"BMI":22.038567493113},{"height":166,"weight":57.5,"BMI":20.8665989258238},{"height":167,"weight":60,"BMI":21.5138585105239},{"height":168,"weight":62.5,"BMI":22.1442743764172},{"height":169,"weight":65,"BMI":22.7583067819754},{"height":170,"weight":61,"BMI":21.1072664359862},{"height":171,"weight":64,"BMI":21.8870763653774},{"height":172,"weight":67,"BMI":22.6473769605192},{"height":173,"weight":65.5,"BMI":21.8851281365899},{"height":174,"weight":67.75,"BMI":22.3774606949399},{"height":175,"weight":70,"BMI":22.8571428571429},{"height":176,"weight":68,"BMI":21.952479338843},{"height":177,"weight":70.5,"BMI":22.503112132529},{"height":178,"weight":73,"BMI":23.0400201994698},{"height":179,"weight":71.5,"BMI":22.3151587029119},{"height":180,"weight":75,"BMI":23.1481481481481},{"height":181,"weight":74,"BMI":22.5878330942279},{"height":182,"weight":76,"BMI":22.9440888781548},{"height":183,"weight":78,"BMI":23.291229956105},{"height":184,"weight":76,"BMI":22.4480151228733},{"height":185,"weight":80,"BMI":23.3747260774288},{"height":186,"weight":79,"BMI":22.8350098277257},{"height":187,"weight":83,"BMI":23.7353084160256},{"height":188,"weight":81,"BMI":22.9176097781802},{"height":189,"weight":83.5,"BMI":23.3756053861874},{"height":190,"weight":86,"BMI":23.8227146814404}]'
    # 索
    _height = float("170")
    _weight = float("77.17") * 2
    _BMI = float("26.7")
    cal_mem_feature_data({"height": _height, "weight": _weight, "bmi": _BMI}, check_std_array=_verify_str)
    # 翟
    _height = float("188")
    _weight = float("105.4") * 2
    _BMI = float("29.82")
    cal_mem_feature_data({"height": _height, "weight": _weight, "bmi": _BMI}, check_std_array=_verify_str)
    # 勇
    _height = float("164")
    _weight = float("75") * 2
    _BMI = float("27.89")
    cal_mem_feature_data({"height": _height, "weight": _weight, "bmi": _BMI}, check_std_array=_verify_str)
